//
//  Network.m
//  base
//
//  Created by Demi on 10/03/2017.
//  Copyright © 2017 Azazie. All rights reserved.
//

#import "Network.h"
#import <pthread/pthread.h>
#import <UIKit/UIKit.h>

#import <ReactiveObjC/ReactiveObjC.h>
#import "ProfileAutoLoader.h"
#import <ReactiveObjC/RACEXTKeyPathCoding.h>
#import <CommonCrypto/CommonDigest.h>
#import "AccessToken.h"
@implementation Network

@end

@implementation Network (AFHTTPSessionManager)

//+ (NSURL *)newApiUrl:(NSURL *)oldUrl{
//    NSString *absoluteString = oldUrl?oldUrl.absoluteString:nil;
//    NSString *newStr = @"https://apix.azazie.com/1.0/";
//    if (!absoluteString) {
//    }
//    else if ([absoluteString isEqualToString:@"https://api.azazie.com/1.0/"]) {
//
//    }else if([absoluteString isEqualToString:@"https://api-p.azazie.com/1.0/"]){
//        newStr = @"https://apix-p.azazie.com/1.0/";
//    }else if ([absoluteString isEqualToString:@"https://api-p2.azazie.com/1.0/"]){
//        newStr = @"https://apix-p2.azazie.com/1.0/";
//    }else{
//        NSArray *urlArr = [absoluteString componentsSeparatedByString:@".azazie.com"];
//        if (urlArr && urlArr.count > 1) {
//            NSString *fir_str = urlArr[0];
//            newStr = [NSString stringWithFormat:@"%@.x.azazie.com/1.0/",fir_str];
//        }
//    }
//    return [NSURL URLWithString:newStr];
//}

+ (void)setAPIRelativeURL:(NSURL *)relativeURL {
    [self.APISession setValue:relativeURL forKeyPath:@keypath(self.APISession, baseURL)];
    [self.APIJSONSession setValue:relativeURL forKeyPath:@keypath(self.APIJSONSession, baseURL)];
    [self.APISessionNew setValue:relativeURL forKeyPath:@keypath(self.APISessionNew, baseURL)];
    [self.APISessionJsonNew setValue:relativeURL forKeyPath:@keypath(self.APISessionJsonNew, baseURL)];
}

+ (AFHTTPSessionManager *)APISession {
    static AFHTTPSessionManager *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        session = [[BaseHTTPSessionManager alloc] init];
    });
    [self sessionSetChecksum:session];
    return session;
}

+ (AFHTTPSessionManager *)APIJSONSession {
    static AFHTTPSessionManager *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        session = [[BaseHTTPSessionManager alloc] initWithBaseURL:nil sessionConfiguration:nil requestSerializer:[AFJSONRequestSerializer serializer]];
    });
    [self sessionSetChecksum:session];
    return session;
}


+ (BaseHTTPSessionManager *)APISessionNew{
    static AFHTTPSessionManager *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        session = [[BaseHTTPSessionManager alloc] init];
    });
    [self sessionSetChecksum:session];
    return session;
}

+ (BaseHTTPSessionManager *)APISessionJsonNew{
    static AFHTTPSessionManager *session = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        session = [[BaseHTTPSessionManager alloc] initWithBaseURL:nil sessionConfiguration:nil requestSerializer:[AFJSONRequestSerializer serializer]];
    });
    [self sessionSetChecksum:session];
    return session;
}

+(void)sessionSetChecksum:(BaseHTTPSessionManager*)session{
    NSDictionary *dic = [self netCheckSum];
    AccessToken *tekne = [AccessToken currentAccessToken];
    [session.requestSerializer setValue:dic[@"x-checksum"] forHTTPHeaderField:@"x-checksum"];
    [session.requestSerializer setValue:dic[@"x-request-time"] forHTTPHeaderField:@"x-request-time"];
    [session.requestSerializer setValue:tekne.isPreviewUser?:@"" forHTTPHeaderField:@"x-preview"];
}

//let appId = md5(时间戳 + 特定字符串 + ip)
//
//时间戳：到秒
//特定字符串：341AE991C9637DD4A12258F3F6FA7DA3
//
//header(
//    "x-request-time" : 时间戳，
//    "x-checksum": appId
//)
+(NSDictionary *)netCheckSum
{
    
    
    NSString *request_time = [self currentTimeStr];
    NSString *appid = [NSString stringWithFormat:@"%@%@",request_time,@"341AE991C9637DD4A12258F3F6FA7DA3"];
    NSString *md5Str = [self md5:appid];
    
    return @{
        @"x-request-time":request_time,
        @"x-checksum":md5Str.lowercaseString,
    };
}

//获取当前时间戳
+ (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

+ (NSString *)md5:(NSString *)string {
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    return result;
}

@end
